package cn.itcast.mq.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.ProcessIdUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取 RabbitTemplate 对象
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        //配置 ReturnCallBack
        rabbitTemplate.setReturnCallback((message, i, s, s1, s2) -> {
            //判断是否是延迟消息
            if(message.getMessageProperties().getReceivedDelay() > 0) {
                //是一个延迟消息，忽略错误提示
                return;
            }
            //记录日志
            log.info("消息发送到队列失败：响应码: {}, 失败原因: {}, 交换机: {}, 路由key: {}, 消息: {}",
                    i, s, s1, s2, message);
            //如果有必要，可以进行消息的重发
        });
    }
}
